import React, {Component} from 'react';
import {StyleSheet, Text, Image, View, ScrollView, ActivityIndicator, findNodeHandle, UIManager } from 'react-native';
import { Button, Divider} from 'react-native-elements';
import Icon from 'react-native-vector-icons/FontAwesome';
import Api from './Api';
import utils from './utils';
import Storage from './Storage';
import Dimensions from 'Dimensions';

export default class NovelArticle extends React.Component {
    static navigationOptions = ({ navigation }) => {
        return {
          header:null,
          title: navigation.getParam('title', ''),
          headerRight: (
                <Button
                  onPress = {() => navigation.navigate('Home')}
                  icon={
                    <Icon
                    name="home"
                    size={25}
                    color="#2089dc"
                  />
                  }
                  type='clear'
                />
          ),
        };
      };
  
    state = { data:[],loaded:false,url:'',showPages:false,fontSize:21,lists:[],reading:'',novel:{},
      href:'',//小说封面首页,Storage 存储的 key
      width:355,
      height:742,
      c_novel:{},
      scrollToReading:false,
      c_page:1,
      touch_s:{pageX:0,pageY:0},
      c_scale:1.5,
      f_height:26,
      marginLeft:0,
      paddingLeft:0,
      pagedLists:[],
      pagedSize:0
    }
    
    showPagesLists = () => {
        this.setState(previousState => {
            return {showPages: !previousState.showPages};
          })
    }

    scrollNovelToPage=(href)=>{
      Storage.getData(href).then(res=>{
        if(res!==null){
          let c_novel=JSON.parse(res);
          if(!this.state.scrollToReading){
            if('c_page' in c_novel && c_novel.c_page>1){
              this.refs.scroll.scrollTo({x:(c_novel.c_page-1)*this.state.width,y:0});
              this.setState({scrollToReading:true,c_page:c_novel.c_page})
            }
          }
        }
      })
    }

    updateNovel = (mergeNovel) => {
      Storage.getData(mergeNovel.href).then(res=>{
        if(res!==null){
          Storage.mergeData(mergeNovel.href,JSON.stringify(mergeNovel))
        }
      })
    }

    layoutNovel = () => {
      const handle = findNodeHandle(this.refs.text1)
      UIManager.measure(handle,(x, y, width, height, pageX, pageY)=>{
        let c_width = this.state.width;
        let c_height = this.state.height;
        let c_scale = this.state.c_scale;
        let f_cols = Math.floor(c_width*10/width);
        let paddingLeft = (c_width - (f_cols * width / 10))/2;
        let f_height = Math.ceil(c_scale*width/10);
        let marginLeft = width/5;
        let f_rows = Math.floor(c_height/f_height);
        let pagedLists = utils.calcParagraphWith(this.state.lists,f_cols,f_rows);
        let pagedSize = pagedLists.length;
        this.setState({pagedLists:pagedLists,pagedSize:pagedSize,f_height:f_height,marginLeft:marginLeft,paddingLeft:paddingLeft});
        this.scrollNovelToPage(this.state.href)
      })
    }
    
    renderText = (index,index2,fontSize,f_height,item,title) => {
      let textIndent = item.indexOf('<>');
      if(index === 0 && index2 === 0){
        return (
          <Text key={index2} style={{paddingLeft:this.state.paddingLeft,lineHeight:f_height}}>{title}</Text>
        )
      }else{
        if(textIndent===0){
          item = item.replace('<>','');
          return (
            <Text key={index2} style={{lineHeight:f_height,paddingLeft:this.state.paddingLeft,marginLeft:this.state.marginLeft,fontSize:fontSize}}>{item}</Text>
          )
        }else{
          return (
            <Text key={index2} style={{lineHeight:f_height,paddingLeft:this.state.paddingLeft,fontSize:fontSize}}>{item}</Text>
          )
        }
      }
      
    }


    touchStart = (event)=>{
      let pageX = event.nativeEvent.pageX,pageY = event.nativeEvent.pageY;
      let touch_s={pageX:pageX,pageY:pageY};
      this.setState({touch_s:touch_s});
    }

    touchEnd = (event)=>{
      let pageX = event.nativeEvent.pageX,pageY = event.nativeEvent.pageY;
      let touch_s = this.state.touch_s;
      let c_page = this.state.c_page;
      let pagedSize = this.state.pagedSize;
      let width = this.state.width + 20;
      let height = this.state.height + 40;

      if(c_page===1){
        if(pageX - touch_s.pageX > width/5){
          this.changePage(this.state.data.prev);
        }
      }

      if(c_page===pagedSize){
        if(touch_s.pageX - pageX > width/5){
          this.changePage(this.state.data.next);
        }
      }

      if(pageX > width*4/10 && pageX < width*6/10 && pageY > height*4/10 && pageY < height*6/10){
        if(Math.abs(pageX-touch_s.pageX)<50){
          this.setState(previousState => {
            return { showPages: !previousState.showPages };
          })
        }
      }
    }


    handleDrag = (event)=>{
      let c_page = event.nativeEvent.contentOffset.x/this.state.width + 1;
      this.updateNovel({c_page:c_page,href:this.state.href});
      this.setState({c_page:c_page})
    }

    componentDidMount(){
      var {height, width} = Dimensions.get('window');
      height = height - 40;
      width = width - 20;
      this.setState({
        width:width,
        height:height
      })

      const { navigation } = this.props;
      const url = navigation.getParam('url', '');
      const href = navigation.getParam('href', '');
      const scroll = navigation.getParam('scroll', '');
      if(scroll===''){
        this.setState({scrollToReading:true})
      }
      this.setState({url:url,href:href})
      Api.articleNovel({url:url})
          .then((res) => {
              let textArr = res.content.replace(/[\r\n]+/g,'\r\n');
              textArr = textArr.split("\r\n")
              textArr=textArr.filter((u)=>{return u.trim()!==''});

              this.updateNovel({href:this.state.href,url:url,reading:res.title});

              this.setState({
                  data:res,
                  lists:textArr,
                  reading:res.title,
                  loaded:true
              })
          })

    }

    changePage=(url)=>{
        if(url){
            this.setState({url:url,showPages:false,loaded:false})
            Api.articleNovel({url:url})
                .then((res) => {
                    let textArr = res.content.replace(/[\r\n]+/g,'\r\n');
                    textArr = textArr.split("\r\n")
                    textArr=textArr.filter((u)=>{return u.trim()!==''});

                    this.updateNovel({href:this.state.href,url:url,reading:res.title,c_page:1});

                    this.setState({
                        data:res,
                        lists:textArr,
                        reading:res.title,
                        c_page:1,
                        loaded:true
                    })
                    this.props.navigation.setParams({ title: res.title });
                })
        }  
    }

    render() {
        let {loaded,data,url,showPages,fontSize,pagedLists,reading,f_height,width,height} = this.state
        return (
          <View style={{ flex: 1 }}>
            {loaded ?
                <View style={{ flex:1,paddingLeft:10,paddingRight:10,marginTop:0,marginBottom:0}}>
                    <View style={{width: 400, height:40,flexDirection: 'row',position:'absolute',top:0}}>
                        <Text
                          ref='text1'
                          style={{fontSize:fontSize,color:'white'}}
                          onLayout={()=>this.layoutNovel()}
                        >超品巫师超品相师超品</Text>
                     </View>
                    <ScrollView ref='scroll' pagingEnabled horizontal onMomentumScrollEnd={this.handleDrag}
                      onTouchEnd={this.touchEnd}
                      onTouchStart={this.touchStart}
                      >
                        {
                            pagedLists.map((item,index) => (
                              <View key={index} style={{width:width,height:height}}>
                                 {
                                   item.map(
                                     (item2,index2) => (this.renderText(index,index2,fontSize,f_height,item2,data.title))
                                   )
                                 }
                              </View>
                            ))
                        }
                    </ScrollView>
                    
                    <View style={{width:width,height:30}}>
                      <Text>{this.state.c_page} / {this.state.pagedSize} 页</Text>
                    </View>

                    {showPages&&(
                    <View style={{height:50,borderTopWidth:1,borderTopColor:'silver',position:'absolute',bottom:0,width:width+20,backgroundColor:'white'}}>
                        <View style={{ flex: 1, justifyContent: "space-between", alignItems: "center", flexDirection: 'row' }}>
                            <Button icon={
    <Icon
      name="arrow-left"
      size={15}
      color="#2089dc"
    />
  } style={{width: 80, height: 50,}} titleStyle={{color:'#2089dc'}} type="clear" onPress={() => this.changePage(data.prev)} title='上一章'/>
                            <Button iconRight={true} icon={
    <Icon
      name="arrow-right"
      size={15}
      color="#2089dc"
    />
  } style={{width: 80, height: 50,}} titleStyle={{color:'#2089dc'}} type="clear" onPress={() => this.changePage(data.next)} title='下一章'/>
                        </View> 
                    </View>
                    )}
                </View>
                :
                <View style={styles.horizontal}>
                    <ActivityIndicator size="small" color="#00ff00" />
                    <Text>Loading...</Text>
                </View>
            }
          </View>
        );
    }
  }

  const styles = StyleSheet.create({
    container: {
      flex: 1,
      flexDirection: "row",
      justifyContent: "center",
      alignItems: "center",
      paddingLeft:5,
      paddingRight:5,
    },
    horizontal: {
      flex: 1,
      justifyContent: 'center',
      alignItems: "center",
      flexDirection: 'column',
      padding: 10
    },
    rightContainer: {
      flex: 1,
      alignItems:"center",
      paddingLeft: 10,
    },
    title: {
      fontSize: 18,
      marginBottom: 8
    },
    year: {
      textAlign: "center"
    },
    thumbnail: {
      width: 53,
      height: 81
    },
    list: {
      paddingTop: 20
    }
  });